import random
import time

import pyautogui
import cv2
import win32api
import win32con
from PIL import ImageGrab

from utils import find_image
class Picker:
    left, top, right, bottom = [0, 0, 0, 0];
    hwnd = -1
    def __init__(self, left, top, right, bottom, hwnd):
        self.left = left if (left >= 0) else 0
        self.top = top if (top >= 0) else 0
        self.right = right if (right <= 1800) else 1800
        self.bottom = bottom if bottom <= 1000 else 1000
        self.hwnd = hwnd
    def pick(self,):
        times = 1
        while times > 0:
            print("开始查找包裹")
            minLocal = self.checkBag()
            if (minLocal == -1 ):
                self.around()
                times -= 1
            else:
                break
        if times == 0:
            return {"state" : "NOT_FIND"}
        if times != 0:
            print("找到了包裹")
        pyautogui.leftClick(self.left + minLocal[0] + 10 , self.top + minLocal[1] + 5 )#模拟鼠标指针 传送到指定坐标
        time.sleep(0.3)
        times = 3
        while times > 0:
            minLocal = self.checkTip()
            if (minLocal == -1 ):
                times -= 1
                print("没找到包裹按钮")
            else:
                pyautogui.leftClick(self.left + minLocal[0] + 36 , self.top + minLocal[1] + 45 )#模拟鼠标指针 传送到指定坐标
                time.sleep(0.3)
                pyautogui.leftClick(self.left + minLocal[0] + 86 , self.top + minLocal[1] + 45 )#模拟鼠标指针 传送到指定坐标
                time.sleep(0.3)
                pyautogui.leftClick(self.left + minLocal[0] + 136 , self.top + minLocal[1] + 45 )#模拟鼠标指针 传送到指定坐标
                time.sleep(0.4)
                break;
        if times == 0:
            print("没找到包裹按钮")
            pyautogui.moveTo(100, 100, 0.2);
            return {"state":"NOT_FIND"}
        time.sleep(2);
        return {"state":"NOT_FIND"}

    def checkBag(self):
        ImageGrab.grab((self.left, self.top, self.right, self.bottom)).save("static/images/img_Winapi.bmp")
        grassImg = cv2.imread("static/images/bag.bmp");
        windowImg = cv2.imread("static/images/img_Winapi.bmp");
        minLocal = find_image.fastFind(windowImg, grassImg);
        return minLocal
    def checkTip(self):
        ImageGrab.grab((self.left, self.top, self.right, self.bottom)).save("static/images/img_Winapi.bmp")
        grassImg = cv2.imread("static/images/pick_tip.bmp");
        windowImg = cv2.imread("static/images/img_Winapi.bmp");
        minLocal = find_image.fastFind(windowImg, grassImg, 0.000000005);
        return minLocal
    def around(self):
        win32api.PostMessage(self.hwnd, win32con.WM_KEYDOWN, 87,0)
        time.sleep(0.3 )
        win32api.PostMessage(self.hwnd, win32con.WM_KEYUP, 87,0)
        win32api.PostMessage(self.hwnd, win32con.WM_KEYDOWN, 83,0)
        time.sleep(0.3 )
        win32api.PostMessage(self.hwnd, win32con.WM_KEYUP, 83,0)
    def rand(self):
        return random.randrange(0, 10) / 100.0
